// pages/shoppingMall/order.js
const app = getApp()
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "填写订单", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent',
      isShare: 0,
    },
    requestUrl: app.baseUrl,
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,
    addressInfo: [],
    btnText: "确认支付",
    goodsArr: [],
    deliveryFee: 0, //配送费设置为0
    total: 0,
    resouceTotal: 0,
    totalNum: 0,
    showCoupon: false,
    cardList: [],
    chooseCardsArr: [], //已选择的优惠卷
    reSourceCardsArr: [], //原始的优惠券列表
    showMonment: false,

    shareTitle: "",
    shareImg: '',
    openid: '',
    is_login: 0,
    noRegisterContent: '',
    orederId: 0,
    flag: 0,
    is_enter: 0, //订单是否确认了支付
    remark: '',
    addressId: 0,
    shop_id: 0
  },
  onPageScroll(t) {
    if (t.scrollTop < 40) {
      topOpacity = 0
      if (this.data.topOpacity != 0) {
        this.setData({
          topOpacity: 0
        })
      }
    } else if (t.scrollTop >= 40) {
      if (topOpacity <= 1) {
        topOpacity = t.scrollTop / 100 - .4
      } else {
        topOpacity = 1
      }
      if (topOpacity <= 1) {
        this.setData({
          topOpacity: topOpacity
        })
      }
    }
  },
  chooseAddress() {
    if (this.data.is_enter == 1) {
      app.showTip('已确认支付的订单无法再更换收货地址了哦');
      return;
    }
    wx.chooseAddress({
      success: (res) => {
        console.log(res)
        this.setData({
          addressInfo: res
        })
      },
      fail: function (err) {
        console.log(err)
      }
    })

    // //缓存orderId
    // wx.setStorageSync('shopOrderId', this.data.orderId);
    // wx.navigateTo({
    //   url: '/pages/shoppingMall/addressManage?shop_id=' + this.data.shop_id
    // });
  },
  //复原所有的优惠券
  resetCardList() {
    var reSourceCardsArr = this.data.reSourceCardsArr;
    this.setData({
      cardList: reSourceCardsArr,
      chooseCardsArr: []
    });
  },
  //删除商品
  del(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    //判断是否只有一个商品了
    if (that.data.goodsArr.length == 1) {
      app.showTip('订单里至少要保留一个商品哦');
      return;
    }
    wx.showModal({
      title: '温馨提示',
      content: '确认删除此商品吗?',
      complete: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '商品删除中...',
            mask: true
          });

          if (that.data.flag == 0) {
            that.setData({
              flag: 1
            });
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'delShoppingMailOrderGoods.php',
              method: 'POST',
              data: {
                'openid': that.data.openid,
                'id': id,
                'shop_id': that.data.shop_id,
                'orderId': that.data.orderId
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                wx.hideLoading();
                app.showTip(res.data.msg);
                if (res.data.status == 1) {
                  //重新赋值后台请求数据
                  that.setData({
                    cardList: res.data.cardList,
                    total: res.data.total,
                    resouceTotal: res.data.total,
                    totalNum: res.data.totalNum,
                    chooseCardsArr: [],
                    goodsArr: res.data.goodsArr
                  });
                }
                that.setData({
                  flag: 0
                });
              },
              fail: function () {
                that.setData({
                  flag: 0
                });
                wx.hideLoading();
              }
            });

          }
        }
      }
    })
  },
  showCoupon() {
    let that = this;
    //判断此订单是否是已确认支付了的订单
    if (that.data.is_enter == 1) {
      app.showTip('此订单为已被确认支付的订单,无法更换优惠券了哦');
      return;
    }
    that.setData({
      showCoupon: true,
      total: that.data.resouceTotal
    })
  },
  closeCoupon() {
    let that = this;
    that.setData({
      showCoupon: false
    })
  },
  closeMonment() {
    let that = this;
    that.setData({
      showMonment: false
    })
  },
  usePro() {
    let that = this;
    that.setData({
      showMonment: true
    })
  },
  //选择优惠券
  chooseCard(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    let status = e.currentTarget.dataset.status;
    if (status == 3) {
      //无法选择
      return;
    }
    //后台请求检测优惠券的可用性
    wx.showLoading({
      title: '代金券状态刷新中...',
      mask: true
    });

    if (that.data.flag == 0) {
      that.setData({
        flag: 1
      });

      //发起网络请求
      wx.request({
        url: that.data.baseUrl + 'checkShoppMailCard.php',
        method: 'POST',
        data: {
          'cardList': JSON.stringify(that.data.cardList),
          'id': id
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          wx.hideLoading();
          if (res.data.status == 1) {
            that.setData({
              cardList: res.data.cardList
            });
          } else {
            //复原选择为初始状态
            that.resetCardList();
            app.showTip(res.data.msg);
          }
          that.setData({
            flag: 0
          });
        },
        fail: function () {
          wx.hideLoading();
          that.setData({
            flag: 0
          });
        }
      });
    }
  },
  //确认选择
  sure() {
    let that = this;
    let newList = that.data.cardList.filter(item => item.choosStatus == 2);
    that.setData({
      chooseCardsArr: newList,
      showCoupon: false
    });
    //确认使用优惠券
    wx.showLoading({
      title: '订单数据更新中...',
      mask: true
    });

    //发起网络请求
    wx.request({
      url: that.data.baseUrl + 'editShopMallPayAmount.php',
      method: 'POST',
      data: {
        'chooseCardsArr': JSON.stringify(newList),
        'orderId': that.data.orderId,
        'shop_id': that.data.shop_id,
        'payAmount': that.data.resouceTotal
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          that.setData({
            total: res.data.total
          });
        } else {
          app.showTip(res.data.msg);
          //复原选择为初始状态
          that.resetCardList();
        }
      },
      fail: function () {
        wx.hideLoading();
      }
    });
  },
  // 支付
  pay() {
    //判断订单金额
    var that = this;

    var checkName = '';
    if (that.data.is_enter == 1) {
      checkName = that.data.addressInfo.name;
    } else {
      if (that.data.addressInfo.name) {
        checkName = that.data.addressInfo.name;
      } else {
        checkName = that.data.addressInfo.userName;
      }
    }
    if (!checkName) {
      app.showTip('请先选择收货地址信息哦');
      return;
    }

    let newList = that.data.cardList.filter(item => item.choosStatus == 2);
    wx.showLoading({
      title: '支付订单生成中...',
      mask: true
    });

    if (that.data.flag == 0) {
      that.setData({
        flag: 1
      });
      var requestAddressInfo = [];
      let addressInfo = that.data.addressInfo;
      if (that.data.is_enter == 1 || addressInfo.name) {
        requestAddressInfo = addressInfo;
      } else {
        let newAddressInfo = {
          id: 0,
          room_number: "",
          name: addressInfo.userName,
          tel: addressInfo.telNumber,
          address: addressInfo.provinceName + addressInfo.cityName + addressInfo.countyName + addressInfo.detailInfo
        }
        requestAddressInfo = newAddressInfo;
      }

      //发起网络请求
      wx.request({
        url: that.data.baseUrl + 'createShopMallPayOrderNumber.php',
        method: 'POST',
        data: {
          'chooseCardsArr': JSON.stringify(newList),
          'orderId': that.data.orderId,
          'shop_id': that.data.shop_id,
          'payAmount': that.data.total,
          'addressInfo': JSON.stringify(requestAddressInfo),
          'remark': that.data.remark,
          'openid': that.data.openid
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          wx.hideLoading();
          app.showTip(res.data.msg);
          if (res.data.status == 1) {
            //支付金额大于0
            var payMoney = res.data.payMoney;
            var payOrderNumber = res.data.payOrderNumber;
            wx.requestPayment({
              'timeStamp': res.data.data.timeStamp,
              'nonceStr': res.data.data.nonceStr,
              'package': res.data.data.package,
              'signType': res.data.data.signType,
              'paySign': res.data.data.paySign,
              'success': function (res) {
                console.log('success');
                var date = new Date();
                var year = date.getFullYear();
                var month = date.getMonth() + 1; // 月份从0开始，所以要加1
                var day = date.getDate();
                var hour = date.getHours();
                var minute = date.getMinutes();
                var second = date.getSeconds();
                if (hour < 10) {
                  hour = '0' + hour;
                }
                if (minute < 10) {
                  minute = '0' + minute;
                }
                if (second < 10) {
                  second = '0' + second;
                }
                var payTime = year + "年" + month + "月" + day + "日 " + hour + ":" + minute + ":" + second;
                wx.redirectTo({
                  url: '/pages/activityCenter/paySuccess?payTime=' + payTime + "&payMoney=" + payMoney +
                    "&payOrderNumber=" + payOrderNumber + "&orderType=shop"
                });
              },
              'fail': function (res) {
                console.log(res);
              },
              'complete': function (res) {
                console.log('complete');
              }
            });
          } else if (res.data.status == 10) {
            //支付金额为0
            setTimeout(function () {
              wx.redirectTo({
                url: '/pages/activityCenter/paySuccess?payTime=' + res.data.payTime +
                  "&payMoney=" + res.data.payMoney + "&payOrderNumber=" + res.data.payOrderNumber + "&orderType=shop"
              });
            }, 1200)
          }
          that.setData({
            flag: 0
          });
        },
        fail: function () {
          wx.hideLoading();
          that.setData({
            flag: 0
          });
        }
      });
    }
  },

  //获取备注信息
  remark(e) {
    var remark = e.detail.value;
    console.log(remark);
    this.setData({
      remark: remark
    });
  },

  preventTouchMove() {
    return false;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;

    //商品id
    var orderId = options.orderId;
    var addressId = options.addressId
    //orderId = 1;
    if (orderId == '' || orderId == null || orderId == undefined) {
      app.showTip('未获取到订单ID哦');
      setTimeout(function () {
        wx.navigateBack({
          delta: 1
        })
      }, 1500);
      return;
    } else {
      that.setData({
        orderId: orderId
      });
    }

    if (addressId != '' && addressId != null && addressId != undefined) {
      that.setData({
        addressId: addressId
      });
    } else {
      addressId = 0;
    }

    //获取商城id
    var shop_id = options.shop_id;
    if (shop_id == '' || shop_id == null || shop_id == undefined) {
      app.showTip('请先选择商城');
      setTimeout(function () {
        wx.navigateBack({
          delta: 1
        })
      }, 1500);
      return;
    }
    that.setData({
      shop_id: shop_id
    });

    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getShoppingMallOrderPageInfo(res.data.openid, orderId, shop_id, addressId);
              },
              fail: function (res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      that.getShoppingMallOrderPageInfo(openid, orderId, shop_id, addressId);
    }

    //调用分享
    that.getShareInfo();
  },

  //获取本页数据
  getShoppingMallOrderPageInfo(openid, orderId, shop_id, addressId) {
    var that = this;
    wx.showLoading({
      title: '数据加载中...',
      mask: true
    });

    //发起网络请求
    wx.request({
      url: that.data.baseUrl + 'getShoppingMallOrderPageInfo.php',
      method: 'POST',
      data: {
        'openid': openid,
        'orderId': orderId,
        'shop_id': shop_id,
        'addressId': addressId
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //重新赋值后台请求数据
          that.setData({
            goodsArr: res.data.goodsArr,
            totalNum: res.data.totalNum,
            total: res.data.total,
            cardList: res.data.cardList,
            is_enter: res.data.is_enter,
            chooseCardsArr: res.data.chooseCardsArr,
            reSourceCardsArr: res.data.cardList,
            resouceTotal: res.data.total,
            addressInfo: res.data.addressInfo
          });
        } else {
          app.showTip(res.data.msg);
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            });
          }, 1500);
        }
      },
      fail: function () {
        wx.hideLoading();
      }
    });
  },

  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function (res) {}
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/index/index',
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})